import 'package:flutter/material.dart';
import 'package:x3_base_package/x3_base_package.dart';
import 'package:x3_business_core/business_common_template/models/business_detailed_order_service.dart';
import 'package:x3_business_core/business_common_template/page/business_detailed_order_page.dart';

/// 作者：william on 2021/3/11 14:22
/// 邮箱：362661044@qq.com
class BusinessCreateMainOrderPage extends StatefulWidget {
  final BusinessDetailedOrderService service;
  final BaseRequestFormProvider baseRequestFormProvider;
  final VoidCallback callback;
  final int groupType;

  // 新建/编辑 页面是否显示保存按钮
  final bool showSaveButton;

  const BusinessCreateMainOrderPage({
    Key key,
    @required this.baseRequestFormProvider,
    @required this.service,
    @required this.groupType,
    this.showSaveButton = true,
    this.callback,
  })  : assert(service != null),
        assert(baseRequestFormProvider != null),
        super(key: key);

  @override
  _BusinessCreateMainOrderPageState createState() => _BusinessCreateMainOrderPageState();
}

class _BusinessCreateMainOrderPageState extends State<BusinessCreateMainOrderPage> with BusinessCreateMainOrder {
  @override
  Widget build(BuildContext context) {
    return buildContent();
  }

  @override
  BaseRequestFormProvider get baseRequestFormProvider => widget.baseRequestFormProvider;

  @override
  String get billsName => widget.service.billsName ?? '';

  @override
  Function(String billsId) get overrideEditPage => null;

  @override
  get callback => widget.callback;

  @override
  BusinessDetailedOrderService get service => widget.service;

  @override
  String get groupType => widget.groupType.toString();

  @override
  bool get showSaveButton => widget.showSaveButton;
}

mixin BusinessCreateMainOrder<T extends StatefulWidget> on State<T> {
  String get billsName;

  String get groupType;

  BaseRequestFormProvider get baseRequestFormProvider;

  BusinessDetailedOrderService get service;

  void Function(String billsId) get overrideEditPage;

  VoidCallback get callback;

  /// 是否显示保存按钮
  bool get showSaveButton;

  /// 主单
  Widget buildContent() {
    return BaseScaffoldComponent(
      title: '新建' + billsName,
      footerWidget: _footerWidget(),
      child: SingleChildScrollView(
        child: BaseCardComponent(child: BaseRequestForm(baseRequestFormProvider: baseRequestFormProvider)),
      ),
    );
  }

  Widget _footerWidget() {
    return Container(
      color: Colors.white,
      child: BaseDrawerBottom(
        close: () => {Navigator.of(context).pop()},
        sureText: '下一步',
        sure: _saveMainOrder,
      ),
    );
  }

  /// 获取主单然后 跳转到子单明细
  void _saveMainOrder() async {
    bool check = baseRequestFormProvider.validationDataSource();
    if (check == true) {
      Map<String, dynamic> data = baseRequestFormProvider.getAllDataMapKey();
      if (groupType != null && groupType != "-2") {
        data.addAll({'groupType': groupType});
      }

      /// 验证数据
      if (data.containsKey('beginDate') && data.containsKey('endDate')) {
        DateTime beginDate = DateTime.tryParse(data.getToString('beginDate')).toLocal();
        DateTime endDate = DateTime.tryParse(data.getToString('endDate')).toLocal();
        bool check = !(endDate.isAtSameMomentAs(beginDate) || endDate.isAfter(beginDate));
        if (check) {
          BaseHttpRequestModel _beginDate = baseRequestFormProvider.requests.firstWhere((element) => element.fieldName == 'beginDate');
          BaseHttpRequestModel _endDate = baseRequestFormProvider.requests.firstWhere((element) => element.fieldName == 'endDate');
          BaseUtils.showToast('${_endDate.name}不能小于${_beginDate.name}');
          return;
        }
      }
      BaseComponentUtils.showLoadingDialog(context);
      BaseHttpResultModel result = await dioUtil.fetch(service.saveMainService.path, method: service.saveMainService.method, params: data);
      BaseComponentUtils.hideLoadingDialog(context);
      if (result.success == true) {
        String billsId = result.data['billsId'];

        /// 如果有回调
        if (overrideEditPage != null) {
          overrideEditPage(billsId);
          return;
        }

        /// 没有回调跳转编辑页面
        service.billsId = billsId;
        service.groupType = groupType;
        BaseRouterUtil().pushReplacement(BusinessDetailedOrderPage(baseRequestFormProvider: baseRequestFormProvider, service: service, isPopReload: true, showSaveButton: showSaveButton)).then((value) {
          if (value == true) {
            if (callback != null) callback();
          }
        });
      }
    }
  }
}
